package org.zjut.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CommonUtil {


    /**
     * 错误信息返回
     * @param errorMsg
     * @return
     */
    public static Map<String,Object> setErrorInfo(String errorMsg){
        Map<String,Object>  errorMap = new HashMap<>();
        errorMap.put("success",false);
        errorMap.put("error",errorMsg);
        return errorMap;
    }

    public static String paramsError(HttpServletRequest request){
        return JSON.toJSONString(CommonUtil.setErrorInfo("请求参数有问题，请注意检查"));
    }


    //获取客户端请求的JSON数据
    public static String getBodyRequest(HttpServletRequest request) {
        // 把reqeust的body读取到StringBuilder
        BufferedReader reader = null;
        try {
            reader = request.getReader();
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();

        char[] buf = new char[1024];
        int rd;
        try {
            while ((rd = reader.read(buf)) != -1) {
                sb.append(buf, 0, rd);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        System.out.println(sb.toString());
        return sb.toString();
    }
}
